package com.example.demo.controller;

import com.example.demo.Provider.AccessProvider;
import com.example.demo.dto.GiteeUser;
import com.example.demo.dto.ProviderTokenDTO;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author redjava
 * @create 2021-07-20 10:58
 */
@Controller
public class AuthorizeController {
    @Autowired
    private ProviderTokenDTO providerTokenDTO;
    @Autowired
    private AccessProvider accessProvider;
    @Autowired
    private UserMapper userMapper;

    @Value("${gitee.client.id}")
    private String clientId;
    @Value("${gitee.client.secret}")
    private String clientSecret;
    @Value("${gitee.redirect.uri}")
    private String redirectUri;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response) {
        providerTokenDTO.setClient_id(clientId);
        providerTokenDTO.setCode(code);
        providerTokenDTO.setRedirect_uri(redirectUri);
        providerTokenDTO.setState(state);
        providerTokenDTO.setClient_secret(clientSecret);
        String accessToken = accessProvider.getToken(providerTokenDTO);
        GiteeUser giteeUser = accessProvider.getUser(accessToken);
        if (giteeUser != null && giteeUser.getId() != null) {
            String accountId = String.valueOf(giteeUser.getId());
            User user = userMapper.isExist(accountId);
            String token = UUID.randomUUID().toString();
            if (user != null) {
                user.setToken(token);
                user.setAvatarUrl(giteeUser.getAvatar_url());
                user.setName(giteeUser.getName());
                user.setGmtModified(System.currentTimeMillis());
                userMapper.update(user);
            } else {
                user.setToken(token);
                user.setName(giteeUser.getName());
                user.setAccountId(accountId);
                user.setGmtCreate(System.currentTimeMillis());
                user.setGmtModified(user.getGmtCreate());
                user.setAvatarUrl(giteeUser.getAvatar_url());
                userMapper.insert(user);
            }
            //登录成功，写cookie和session
            response.addCookie(new Cookie("token", token));
            return "redirect:/";
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
